﻿namespace WebExample.Controllers
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Web.Mvc;
    using LinqToLdapExtensions;
    using LinqToLdapExtensions.Domain;

    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
    public class HomeController : Controller
    {
        private readonly DirectoryContextUnitOfWork unitOfWork;

        public HomeController(DirectoryContextUnitOfWork unit)
        {
            if (unit == null)
            {
                throw new ArgumentNullException("unit");
            }

            this.unitOfWork = unit;
        }

        public ActionResult Index()
        {
            var counter = Session["countHits"] == null ? 0 : int.Parse(Session["countHits"].ToString());
            counter++;
            this.Session["countHits"] = counter;

            ViewBag.FactoryKey = ((DirectoryContextFactory)this.unitOfWork.Factory).Key;
            return this.View(counter);
        }

        public ActionResult IntegrationTestUserList()
        {
            var result = this.unitOfWork.CurrentContext.Query<InetOrgPerson>(
                    System.DirectoryServices.Protocols.SearchScope.OneLevel)
                           .Take(100).ToList();

            return this.View(result);
        }

        public ActionResult IntegrationTestUserDetails(string id)
        {
            id = id.Replace('_', '.'); // stupid dots in username...
            var result = this.unitOfWork.CurrentContext.Query<InetOrgPerson>(
                System.DirectoryServices.Protocols.SearchScope.OneLevel)
                .FirstOrDefault(p => p.Uid.Equals(id, StringComparison.OrdinalIgnoreCase));

            return this.View(result);
        }
    }
}
